<template>
  <el-container class="main-bg">
    <!--主内容 -->
    <el-aside style="width:200px;background-color: #253b40;">
      <el-container>
        <el-header>
          <el-tooltip class="item" effect="dark" placement="right" offset="">
            <div slot="content">
              <!-- <div class="tool" @click="$router.push({name: '个人资料',path:'/company/personInfo'})">
                <i class="el-icon-nav-people_fill" style="margin:0px 5px;"></i>个人资料
              </div>
              <div class="tool">
                <i class="el-icon-nav-shezhi" style="margin:0px 5px;"></i>密码管理
              </div> -->
              <div class="tool" @click="exit">
                <i class="el-icon-nav-084tuichu" style="margin:0px 5px;"></i>注销退出
              </div>
            </div>
            <div class="role">
              <span>{{userNickName}}</span>
            </div>
          </el-tooltip>
        </el-header>
        <el-main style="padding:0px;">
          <el-menu :default-active="$route.path" id="collapse" :collapse="isCollapse" class="el-menu-demo" mode="vertical" @open=""
            @close="" unique-opened background-color="#253b40" text-color="#8eafd1" active-text-color="#e8f3ff" router style="border-right: solid 1px #253b40;">
            <nav-item v-for="(item, index) in permissionRoutes" v-if="item.root" :item="item" :navIndex="String(index)" :key="index">
            </nav-item>
          </el-menu>
        </el-main>
        <!-- <el-footer style="height: 81px;padding:0;">
          <div class="timeVersion">
            <div class="version">当前版本V1.0</div>
            <div class="date">{{date}}</div>
            <div class="time">{{time}}</div>
          </div>
        </el-footer> -->
      </el-container>
    </el-aside>
    <el-main style="padding:0px;">
      <section class="main_content" style="">
        <!-- <transition name="fade" mode="out-in"> -->
        <router-view ref='monitor'></router-view>
        <!-- </transition> -->
      </section>
      <div class="clean_cache">
        <el-button size="mini" type="danger" @click="handleCleanCache">清除缓存</el-button>
      </div>
    </el-main>
  </el-container>
</template>


<script>
  import axios from 'axios'
  import navItem from "./Commons/navItem.vue";
  import {
    mapGetters
  } from "vuex";
  import {
    wsapi,
    get,
    post,
    pat,
    del,
    common,
    getRefresh
  } from "../../api/api";

  export default {
    components: {
      navItem
    },
    inject: ['reload'],
    data() {
      return {
        ws: "",
        input: "",
        inout: true,
        uniqueOpened: true,
        //导航栏收缩
        isCollapse: false,
        //路径栏数据
        pathVisible: true,
        time: "",
        date: "",
        bellMessage: [],
        isdot: false,
        isAllRead: [],
        //公告数据
        isModule3Close: true,
        userNickName: "",
        permissionList: [],
        permissionRoutes: [],
      };
    },
    // computed: {
    //   ...mapGetters({
    //     username: "getUsername"
    //   })
    // },
    methods: {
      //-------清理缓存-----------
      handleCleanCache() {
        return new Promise((resolve, reject) => {
          axios.get("http://www.xiaoans.com/xas/common/cache/clean?type=0", {
            withCredentials:false
          }).then(resdata => {
            let self = function () {
              this.$router.push({
                path: '/home'
              });
            }.bind(this);
            let error = function () {
              alert(resdata.msg)
            }.bind(this);
            let success = function () {
              if (resdata.code == 1) {}
            }.bind(this);
            common(self)(error)(success)(resdata);
            resolve();
          });
        });
      },
      //-------消息已读未读功能的实现-----------
      messageEffects(event, item) {
        if (item.isRead == 0) {
          //console.log(item);
          var index = "";
          this.isAllRead.forEach(function (el, i) {
            if (el.id == item.id) {
              index = i;
            }
          });
          this.isAllRead.splice(index, 1);
          if (this.isAllRead.length == 0) {
            this.isdot = false;
          }
          item.isRead = 1;
          var noticeId = [];
          noticeId.push(item.id);
          var command = 0; //0 设为已读, 1 设为未读, 2 删除
          pat("/common/userNotices?", {
            notices: noticeId,
            command: command
          }).then(resdata => {
            //console.log(resdata);
          });
        }
      },
      //注销实现
      exit() {
        this.$router.push({
          path: "/home"
        });
        localStorage.removeItem("token");
        localStorage.removeItem("permissionList");
        localStorage.removeItem("userInfo");
        sessionStorage.removeItem("islogin");
        sessionStorage.removeItem("username");
        sessionStorage.removeItem("person_info");
        this.$store.state.Auth.person_info = {};
        this.$store.state.Auth.userInfo.role = null;
        this.$store.state.Auth.username = "";
      },
      //--------日期时间版本的实现------
      timeVersion() {
        var week = [
          "星期日",
          "星期一",
          "星期二",
          "星期三",
          "星期四",
          "星期五",
          "星期六"
        ];
        var today = new Date(); //定义日期对象
        var yyyy = today.getFullYear(); //通过日期对象的getFullYear()方法返回年
        var MM = today.getMonth() + 1; //通过日期对象的getMonth()方法返回年
        var dd = today.getDate(); //通过日期对象的getDate()方法返回年
        var hh = today.getHours(); //通过日期对象的getHours方法返回小时
        var mm = today.getMinutes(); //通过日期对象的getMinutes方法返回分钟
        var ss = today.getSeconds(); //通过日期对象的getSeconds方法返回秒
        MM = this.checkTime(MM);
        dd = this.checkTime(dd);
        mm = this.checkTime(mm);
        ss = this.checkTime(ss);
        var day = week[today.getDay()];
        this.date = yyyy + "-" + MM + "-" + dd + " " + day;
        this.time = hh + ":" + mm + ":" + ss;
      },
      checkTime(i) {
        if (i < 10) {
          i = "0" + i;
        }
        return i;
      },
      //-------------消息推送-----------------
      getMessage() {
        this.ws = wsapi();
        let ws = this.ws;
        let number = 0;
        ws.onopen = function (evt) {
          //console.log("连接到websocket服务端");
          //ws.send('{"manager_id": "1"}');
          setInterval(function () {
            if (number >= 100) number = 0;
            ws.send(`{"beat":"执行代码00${number}"}`);
            number++;
          }, 480000);
        };
        ws.onmessage = function (evt) {
          console.log("接收服务端推送的信息: " + evt.data);
          switch (evt.data) {
            case "open":
              var str = {
                token: localStorage.getItem("token")
              };
              str = JSON.stringify(str);
              //console.log(str);
              ws.send(str);
              break;
            case "ok":
              break;
            default:
              var data = JSON.parse(evt.data);
              var type = "";
              if (data.level == 0) type = "success";
              else if (data.level == 1) type = "warning";
              else type = "error";
              this.$notify({
                message: data.message,
                type: type,
                duration: 10000,
                showClose: true
              });
              this.$refs.notify.play();
              break;
          }
        }.bind(this);
        ws.onclose = function (evt) {
          // console.log('close' + evt.data)
        };
      },
      getBellMessage() {
        return new Promise((resolve, reject) => {
          get("/common/userNotices?mode=0").then(resdata => {
            let self = function () {
              getRefresh(this.getBellMessage);
            }.bind(this);
            let error = function () {
              this.deviceList = [];
            }.bind(this);
            let success = function () {
              if (resdata.code == 0) {
                this.bellMessage = resdata.data.notices;
              } else {
                alert("无数据!");
              }
            }.bind(this);
            common(self)(error)(success)(resdata);
            resolve();
          });
        });
      },
      //-------查看更多信息--------
      moreMessage() {
        this.$router.push({
          path: "/company/message"
        });
      },
      //------------------------------
      //---------权限渲染菜单--------
      getPermissionListByUid() {
        return new Promise((resolve, reject) => {
          get("/common/xasPermissionListByUid").then(resdata => {
            let self = function () {
              getRefresh(this.getPermissionListByUid);
            }.bind(this);
            let error = function () {
              alert(resdata.msg)
            }.bind(this);
            let success = function () {
              if (resdata.code == 1) {

              } else {
                alert("无数据!");
              }
            }.bind(this);
            common(self)(error)(success)(resdata);
            resolve();
          });
        });
      },
    },
    async mounted() {
      //console.log(navigator.userAgent)
      if (
        navigator.userAgent.match(
          /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|wOSBrowser|BrowserNG|WebOS)/i
        )
      ) {} else {
        // var link = document.createElement("link");
        // link.setAttribute("type", "text/css");
        // link.setAttribute("rel", "stylesheet");
        // link.setAttribute("href", " http://47.104.4.242/static/table.css");
        // link.setAttribute("media", "screen");
        // document.head.appendChild(link);
      }
      //日期时间版本的显示
      setInterval(this.timeVersion, 1000);
      // await this.getBellMessage();
      // await this.getMessage();
      this.userNickName = JSON.parse(localStorage.getItem('userInfo')).nickName;
      this.permissionList = JSON.parse(localStorage.getItem("permissionList"));
      var routes = [];
      for (var i = 0; i < this.permissionList.length; i++) {
        var midList = {}
        midList.path = this.permissionList[i].url;
        midList.name = this.permissionList[i].name;
        midList.root = true;
        midList.component = resolve => require([this.permissionList[i].component], resolve);
        midList.children = [];
        for (var j = 0; j < this.permissionList[i].xasPermission.length; j++) {
          var thrList = {}
          thrList.path = this.permissionList[i].xasPermission[j].url;
          thrList.name = this.permissionList[i].xasPermission[j].name;
          thrList.component = resolve => require([this.permissionList[i].xasPermission[j].component], resolve);
          midList.children.push(thrList)
        }
        routes.push(midList)
      }
      this.permissionRoutes = routes;
    },
    watch: {}
  };

</script>

<style lang="scss">
  /* 主页导航效果*/

  #collapse {
    .is-active:hover {
      color: #323c3e !important;
      background-color: #ecf5ff !important;
    }
    .is-active:focus {
      color: #323c3e !important;
      background-color: #ecf5ff !important;
    }
    .el-submenu__title:hover {
      color: #323c3e !important;
      background-color: #ecf5ff !important;
    }
  }

  .el-menu {
    // background: #323c3e;
    text-align: left;
  }

  .el-menu-item {
    text-align: center;
  }

  .el-menu-item:hover {
    color: #323c3e !important;
    background-color: #ecf5ff !important;
  }

  /* 时间提示*/

  .timeVersion {
    position: relative; // text-align: right;
    padding-top: 10px;
    background-color: rgb(37, 59, 64);
    user-select: none;
    .time {
      letter-spacing: 0.1em;
      font-size: 1.4rem;
      color: white;
      line-height: 36px;
    }
    .date {
      letter-spacing: 0.05em;
      font-size: 1.2rem;
      line-height: 16px;
      color: white;
    }
    .version {
      letter-spacing: 0.05em;
      font-size: 1.4rem;
      color: white;
    }
  }

  /* 右上信息栏CSS*/

  .el-tooltip__popper {
    margin-top: 5px !important; // width: 150px;
    .tool {
      font-size: 1.3rem;
      height: 26px;
      line-height: 26px;
      width: 140px;
      &:hover {
        background-color: rgba(242, 242, 242, 0.1);
        color: #66b1ff;
        cursor: pointer;
      }
    }
  }

  .main-bg {
    width: 100%;
    height: 100%; // background-color: #e6eaee;
    .role {
      display: block;
      height: 60px;
      width: 100%;
      line-height: 40px;
      padding: 10px;
      font-size: 1.6rem;
      font-weight: bold;
      color: white;
      z-index: 5;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      cursor: pointer;
    }

    .head_top .exit {
      float: right;
      width: auto;
      padding: 10px;
      border-left: 1px solid white;
      .button {
        width: 50px;
        padding: 11.5px;
        border-radius: 5px;
      }
    }
    .Notification {
      @extend .role;
      width: 60px !important;
    }
    /*以下是主要内容*/
    .main {
      height: 100%;
      overflow: hidden;
      display: -webkit-flex;
      /* 新版本语法: Chrome 21+ */
      display: flex;
      /* 新版本语法: Opera 12.1, Firefox 22+ */
      display: -moz-box;
      /* 老版本语法: Firefox (buggy) */
      display: -ms-flexbox;
      /* 混合版本语法: IE 10 */
      .collapse_icon {
        &:hover {
          transform: scale(1.4);
        }
        font-size: 3.2rem;
        bottom: 0px;
        right: 0px;
        color: white;
        position: absolute;
        transition: all 0.5s;
      }
    }
    .clean_cache {
      position: absolute;
      top: 12px;
      right: 20px;
    }
    .main_content {
      -webkit-flex: 1;
      /* Chrome */
      -ms-flex: 1;
      /* IE 10 */
      flex: 1;
      /* NEW, Spec - Opera 12.1, Firefox 20+ */
      -moz-box-flex: 1;
      /* OLD - Firefox 19- */
      display: block;
      overflow-y: auto;
      background: #e0e9e9;
      height: 100%;
      padding: 0px;
      margin: 0px;
      background-color: rgba(242, 242, 242, 0.1);
    }
    /* 以下是脚部内容 */
    .el-submenu .el-menu-item {
      padding-left: 40px !important;
      min-width: 88px !important;
      z-index: 1000;
    }

    .el-submenu .el-menu-item-demo {
      min-width: 88px !important;
    }
    /* 组件动态CSS效果*/
    .fade-enter-active,
    .fade-leave-active {
      transition: all 0.5s;
    }

    .fade-enter,
    .fade-leave-to {
      opacity: 0;
      transform: scale(0);
    }
  }

  /* 美化滚动条（全局变量）*/

  ::-webkit-scrollbar {
    width: 14px;
    height: 14px;
  }

  ::-webkit-scrollbar-track,
  ::-webkit-scrollbar-thumb {
    border-radius: 999px;
    border: 5px solid transparent;
  }

  ::-webkit-scrollbar-track {
    box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2) inset;
  }

  ::-webkit-scrollbar-thumb {
    min-height: 20px;
    background-clip: content-box;
    box-shadow: 0 0 0 5px rgba(0, 0, 0, 0.2) inset;
  }

  ::-webkit-scrollbar-corner {
    background: transparent;
  }

  /* 全局变量*/

  * {
    padding: 0px;
    margin: 0px;
    border: 0px;
    box-sizing: border-box;
    font-family: "Microsoft Yahei";
  }

  html {
    height: 100%;
  }

  /* @media screen and (min-width: 0px) and (max-device-width: 1000px) {
  html {
    font-size: 62.5%;
  }
} */

  @media screen and (min-width: 0px) and (max-device-width: 2000px) {
    html {
      font-size: 62.5%;
    }
  }

  body {
    height: 100%;
  }

  #app {
    height: 100%;
  }

  a {
    text-decoration: none;
  }

  .float_left {
    float: left;
  }

  .float_right {
    float: right;
  }

</style>
